/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */

let tree = {
    val: 1,
    left: {
        val: 2,
        left: {
            val: 4,
            left: null,
            right: null
        },
        right: {
            val: 5,
            left: null,
            right: null
        }
    },
    right: {
        val: 3,
        left: {
            val: 6,
            left: null,
            right: null
        },
        right: {
            val: 7,
            left: null,
            right: null
        }
    }
}


/**
 * 递归实现
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function (root) {
    let ans = []
    if (root) {
        const traversal = (node, ans) => {
            if (node.left) traversal(node.left, ans)
            if (node.right) traversal(node.right, ans)
            ans.push(node.val)

        }
        traversal(root, ans)
    }
    return ans
};


/**
 * 非递归实现
 * @param {TreeNode} root
 * @return {number[]}
 */
var _postorderTraversal = function (root) {
    let ans = []
    let stack = []
    stack.push(root)
    if (root) {
        while(stack.length>0){
            let tmp = stack.pop()
            ans.push(tmp.val)
            if(tmp.left) stack.push(tmp.left)
            if(tmp.right) stack.push(tmp.right)
        }

    }
    return ans.reverse()
}
console.log(_postorderTraversal(tree));